var salt = sessionStorage.getItem('usersalt');

layui.use(['form', 'layer', 'laydate'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		laydate = layui.laydate,
		$ = layui.jquery;
		
	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);
	}
	
	laydate.render({
		elem: '#workTime',
		trigger: 'click'
	});
});

/*------------单位节点树.start------------*/
function showWorkUnitTree(){
	$('#workUnitTree').show();
}

var company;
function getAllCompany() {
	$.ajax({
		url: url + 'baseEnt/getAllEnt',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
		},
		success: function(data) {
			$('#workUnitTree').empty();
			if(data.code == 0) {
				company = data.data;
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}
getAllCompany();

var setting = {
	data: {
		simpleData: {
			enable: true
		}
	},
	check: {
		enable: true,
		chkStyle: "radio", //单选框
		radioType: "all" //对所有节点设置单选
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

$.fn.zTree.init($("#workUnitTree"), setting, company);
function zTreeOnCheck(event, treeId, treeNode) {
	var checked = treeNode.checked;
	if (checked) {
		$('#workUnit').val(treeNode.name);
	} else {
		$('#workUnit').val("");
	}
	$('#workUnitTree').hide();

};

function getUnitTreeVal() {
	var unitTreeVal = [];
	var treeObj = $.fn.zTree.getZTreeObj("workUnitTree");
	var nodes = treeObj.getCheckedNodes(true);
	for(var i = 0; i < nodes.length; i++) {
		unitTreeVal.push(nodes[i].id); //获取选中节点的值
	}
	return unitTreeVal;
}
/*------------单位节点树.end------------*/

/*------------岗位节点树.start------------*/
function showJobUnitTree(){
	$('#jobUnitTree').show();
}

var job;
function getAllJob() {
	$.ajax({
		url: url + 'post/getAllEnt',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
		},
		success: function(data) {
			$('#jobUnitTree').empty();
			if(data.code == 0) {
				job = data.data;
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}
getAllJob();

var jobSetting = {
	check: {
		enable: true,
		chkboxType: { "Y": "", "N": "" }
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		onCheck: jobZTreeOnCheck
	}
};

$.fn.zTree.init($("#jobUnitTree"), jobSetting, job);
function jobZTreeOnCheck(event, treeId, treeNode) {
	var nval = "";
	var treeObj = $.fn.zTree.getZTreeObj("jobUnitTree");
	var nodes = treeObj.getCheckedNodes(true);
	for(var i = 0; i < nodes.length; i++) {
		nval += nodes[i].name + ",";
	}
	$('#jobUnit').val(nval.substr(0, nval.length - 1));
};

function getJobTreeVal() {
	var unitTreeVal = [];
	var treeObj = $.fn.zTree.getZTreeObj("jobUnitTree");
	var nodes = treeObj.getCheckedNodes(true);
	for (var i = 0; i < nodes.length; i++) {
		unitTreeVal.push(nodes[i].id); //获取选中节点的值
	}
	return unitTreeVal;
}
/*------------岗位节点树.end------------*/

/*------------添加JSA分析表.start------------*/

var jsaAnalyze = {id : "",recordNumber : "",workEntId : "",workTime : "",task : "",analyzeName : "",analyzeJobId : "",analyzeUsers : "",
	taskAttribute : "",otherTaskAttribute : "",taskCondition : "",prepareWork : "",workStep : "",completeSurvey : "",
	peopleFactor : "",thingFactor : "",environmentFactor : "",manageFactor : "",otherDangerFactor : "",accidentType : "",pivotalMeasure : "",
	dangerDescribe : "",emergencyResponse : "",rescueMeasures : "",safetyMeasures : "",improvementMeasure : "",workManageUser : "",
	workHandleUser : "",workTutelageUser : ""
};

function addAnalyze(){
	var bool = checkoutParam();
	if (!bool) {
		return;
	}
	$.ajax({
		url: url + 'jsaAnalyze/add',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			Token: salt,
			jsaAnalyzeStr: JSON.stringify(jsaAnalyze)
		},
		success: function(data) {
			if(data.code == 0) {
				var str = "新增JSA分析表提交成功！";
				if (analyzeId != "") {
					str = "修改JSA分析表提交成功！";
				}
				layer.confirm(str, {
					btn: ['确定'] //按钮
				}, function() {
					location.href = "../list/list.html";
				}, function() {
				});
			} else {
				layer.msg(data.msg);
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}

//校验参数合法性
function checkoutParam(){
	if (analyzeId != false) {//编辑
		jsaAnalyze.id = analyzeId;
	}
	
	jsaAnalyze.recordNumber = $.trim($("#recordNumber").val());//记录编号
	if (jsaAnalyze.recordNumber == "") {
		layer.msg('请输入记录编号');
		return false;
	}
	
	jsaAnalyze.workEntId = getUnitTreeVal().toString();//作业单位id
	if (jsaAnalyze.workEntId == 0 || jsaAnalyze.workEntId == "") {
		if (analyzeId != false) {//编辑
			jsaAnalyze.workEntId = workEntId;
		} else {
			layer.msg('请选择作业单位');
			return false;
		}
	}
	
	jsaAnalyze.workTime = $.trim($("#workTime").val());//作业日期
	if (jsaAnalyze.workTime == "") {
		layer.msg('请选择作业日期');
		return false;
	}
	
	jsaAnalyze.task = $.trim($("#task").val());//工作任务
	if (jsaAnalyze.task == "") {
		layer.msg('请输入任务描述');
		return false;
	}
	
	jsaAnalyze.analyzeName = $.trim($("#analyzeName").val());//分析人姓名
	if (jsaAnalyze.analyzeName == "") {
		layer.msg('请输入分析人姓名');
		return false;
	}
	
	jsaAnalyze.analyzeJobId = getJobTreeVal().toString();//岗位id
	if (jsaAnalyze.analyzeJobId == 0 || jsaAnalyze.analyzeJobId == "") {
		if (analyzeId != false) {//编辑
			jsaAnalyze.analyzeJobId = analyzeJobId;
		} else {
			layer.msg('请选择岗位');
			return false;
		}
	}
	
	jsaAnalyze.analyzeUsers = $.trim($("#analyzeUsers").val());//参加分析人员姓名
	if (jsaAnalyze.analyzeUsers == "") {
		layer.msg('请输入参加分析人员姓名');
		return false;
	}
	
	/*------------工作任务属性.start------------*/
	var attributeArr=new Array();  
	$('input[name="attribute"]:checked').each(function(){  
	    attributeArr.push($(this).val());
	    if ($(this).val() == 0) {
	    	jsaAnalyze.otherTaskAttribute = $.trim($("#otherTaskAttribute").val());
	    	if (jsaAnalyze.otherTaskAttribute == "") {
	    		layer.msg('请输入其他要求');
				return false;
	    	}
	    }
	});
	jsaAnalyze.taskAttribute = attributeArr.join(",");
	if (jsaAnalyze.analyzeUsers == "") {
		layer.msg('请选择工作任务属性');
		return false;
	}
	/*------------工作任务属性.end------------*/
	
	/*------------工作任务环境状况描述.start------------*/
	var conditionArr=new Array();  
	$('input[name="condition"]:checked').each(function(){  
	    conditionArr.push($(this).val());
	});
	jsaAnalyze.taskCondition = conditionArr.join(",");
	if (jsaAnalyze.taskCondition == "") {
		layer.msg('请选择工作任务属性');
		return false;
	}
	/*------------工作任务环境状况描述.end------------*/
	
	jsaAnalyze.prepareWork = $.trim($("#prepareWork").val());//准备工作
	if (jsaAnalyze.prepareWork == "") {
		layer.msg('请输入准备工作内容');
		return false;
	}
	
	jsaAnalyze.workStep = $.trim($("#workStep").val());//主要施工作业步骤
	if (jsaAnalyze.workStep == "") {
		layer.msg('请输入主要施工作业步骤');
		return false;
	}
	
	jsaAnalyze.completeSurvey = $.trim($("#completeSurvey").val());//完工检查
	if (jsaAnalyze.completeSurvey == "") {
		layer.msg('请输入完工检查内容');
		return false;
	}
	
	/*------------人的危害因素.start------------*/
	var peopleFactorArr=new Array();  
	$('input[name="peopleFactor"]:checked').each(function(){  
	    peopleFactorArr.push($(this).val());
	});
	jsaAnalyze.peopleFactor = peopleFactorArr.join(",");
	if (jsaAnalyze.peopleFactor == "") {
		layer.msg('请选择人的因素');
		return false;
	}
	/*------------人的危害因素.end------------*/
	
	/*------------物的危害因素.start------------*/
	var thingFactorArr=new Array();  
	$('input[name="thingFactor"]:checked').each(function(){  
	    thingFactorArr.push($(this).val());
	});
	jsaAnalyze.thingFactor = thingFactorArr.join(",");
	if (jsaAnalyze.thingFactor == "") {
		layer.msg('请选择物的因素');
		return false;
	}
	/*------------物的危害因素.end------------*/
	
	/*------------环境危害因素.start------------*/
	var environmentFactorArr=new Array();  
	$('input[name="environmentFactor"]:checked').each(function(){  
	    environmentFactorArr.push($(this).val());
	});
	jsaAnalyze.environmentFactor = environmentFactorArr.join(",");
	if (jsaAnalyze.environmentFactor == "") {
		layer.msg('请选择环境因素');
		return false;
	}
	/*------------环境危害因素.end------------*/
	
	/*------------管理危害因素.start------------*/
	var manageFactorArr=new Array();  
	$('input[name="manageFactor"]:checked').each(function(){  
	    manageFactorArr.push($(this).val());
	    if ($(this).val() == 0) {
	    	jsaAnalyze.otherDangerFactor = $.trim($("#otherDangerFactor").val());
	    	if (jsaAnalyze.otherDangerFactor == "") {
	    		layer.msg('请输入识别的其他危害因素');
				return false;
	    	}
	    }
	});
	jsaAnalyze.manageFactor = manageFactorArr.join(",");
	if (jsaAnalyze.manageFactor == "") {
		layer.msg('请选择管理因素');
		return false;
	}
	/*------------管理危害因素.end------------*/
	
	/*------------可能造成的事故类型.start------------*/
	var accidentTypeArr=new Array();  
	$('input[name="accidentType"]:checked').each(function(){  
	    accidentTypeArr.push($(this).val());
	});
	jsaAnalyze.accidentType = accidentTypeArr.join(",");
	if (jsaAnalyze.accidentType == "") {
		layer.msg('请选择事故类型');
		return false;
	}
	/*------------可能造成的事故类型.end------------*/
	
	jsaAnalyze.pivotalMeasure = $.trim($("#pivotalMeasure").val());//关键作业步骤，主要风险及控制措施
	if (jsaAnalyze.pivotalMeasure == "") {
		layer.msg('请输入关键作业步骤，主要风险及控制措施');
		return false;
	}
	
	jsaAnalyze.dangerDescribe = $.trim($("#dangerDescribe").val());//险情描述
	if (jsaAnalyze.dangerDescribe == "") {
		layer.msg('请输入可能发生的险情');
		return false;
	}
	
	jsaAnalyze.emergencyResponse = $.trim($("#emergencyResponse").val());//应急处置措施
	if (jsaAnalyze.emergencyResponse == "") {
		layer.msg('请输入应急处置措施');
		return false;
	}
	
	jsaAnalyze.rescueMeasures = $.trim($("#rescueMeasures").val());//应急救援措施
	if (jsaAnalyze.rescueMeasures == "") {
		layer.msg('请输入应急救援措施');
		return false;
	}
	
	jsaAnalyze.safetyMeasures = $.trim($("#safetyMeasures").val());//现场维护安全措施
	if (jsaAnalyze.safetyMeasures == "") {
		layer.msg('请输入现场维护安全措施');
		return false;
	}
	
	jsaAnalyze.improvementMeasure = $.trim($("#improvementMeasure").val());//建议改进措施
	if (jsaAnalyze.improvementMeasure == "") {
		layer.msg('请输入建议改进措施');
		return false;
	}
	
	jsaAnalyze.workManageUser = $.trim($("#workManageUser").val());//作业管理人员
	if (jsaAnalyze.workManageUser == "") {
		layer.msg('请输入作业管理人员姓名');
		return false;
	}
	
	jsaAnalyze.workHandleUser = $.trim($("#workHandleUser").val());//作业操作人员
	if (jsaAnalyze.workHandleUser == "") {
		layer.msg('请输入作业操作人员姓名');
		return false;
	}
	
	jsaAnalyze.workTutelageUser = $.trim($("#workTutelageUser").val());//作业监护人员
	if (jsaAnalyze.workTutelageUser == "") {
		layer.msg('请输入作业监护人员姓名');
		return false;
	}
	return true;
}
/*------------添加JSA分析表.end------------*/

/*-------------编辑获取值.start-------------*/
var analyzeId = getQueryVariable("id");
var workEntId,analyzeJobId;
if (analyzeId != false) {//编辑
	$("#pageTitle").html("编辑JSA分析表");
	$.ajax({
		url: url + 'jsaAnalyze/getInfo',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			Token: salt,
			id : analyzeId,
			type : 2
		},
		success: function(data) {
			if (data.code == 0) {
				initParam(data.data);
			} else {
				setTimeout(function(){
					layer.msg(data.msg);
				}, 1000);
				$("#pageTitle").html("新增JSA分析表");
				analyzeId = false;		
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
} else {
	$("#pageTitle").html("新增JSA分析表");
}

//编辑时赋值
function initParam(data){
	$("#recordNumber").val(data.recordNumber);//记录编号
	$("#workUnit").val(data.workEntName);//作业单位名称
	workEntId = data.workEntId;//作业单位id
	$("#workTime").val(data.workTime);//作业日期
	$("#task").val(data.task);//工作任务
	$("#analyzeName").val(data.analyzeName);//分析人姓名
	$("#jobUnit").val(data.analyzeJobName);//分析人岗位名称
	analyzeJobId = data.analyzeJobId;//岗位id
	$("#analyzeUsers").val(data.analyzeUsers);//参加分析人员姓名
	
	
	/*------------工作任务属性.start------------*/
	var attributeArr = data.taskAttribute.split(",");
	$.each(attributeArr,function(i,item){
		$("input[name='attribute'][value="+item+"]").prop("checked",true);
		if (item == 0) {
			$("#otherTaskAttribute").val(data.otherTaskAttribute);
		}
	});
	/*------------工作任务属性.end------------*/
	
	/*------------工作任务环境状况描述.start------------*/
	var conditionArr = data.taskCondition.split(",");
	$.each(conditionArr,function(i,item){
		$("input[name='condition'][value="+item+"]").prop("checked",true);
	});
	/*------------工作任务环境状况描述.end------------*/
	
	$("#prepareWork").val(data.prepareWork);//准备工作
	$("#workStep").val(data.workStep);//主要施工作业步骤
	$("#completeSurvey").val(data.completeSurvey);//完工检查
	
	/*------------人的危害因素.start------------*/
	var peopleFactorArr = data.peopleFactor.split(",");  
	$.each(peopleFactorArr,function(i,item){
		$("input[name='peopleFactor'][value="+item+"]").prop("checked",true);
	});
	/*------------人的危害因素.end------------*/
	
	/*------------物的危害因素.start------------*/
	var thingFactorArr = data.thingFactor.split(",");  
	$.each(thingFactorArr,function(i,item){
		$("input[name='thingFactor'][value="+item+"]").prop("checked",true);
	});
	/*------------物的危害因素.end------------*/
	
	/*------------环境危害因素.start------------*/
	var environmentFactorArr = data.environmentFactor.split(",");  
	$.each(environmentFactorArr,function(i,item){
		$("input[name='environmentFactor'][value="+item+"]").prop("checked",true);
	});
	/*------------环境危害因素.end------------*/
	
	/*------------管理危害因素.start------------*/
	var manageFactorArr = data.manageFactor.split(",");  
	$.each(manageFactorArr,function(i,item){
		$("input[name='manageFactor'][value="+item+"]").prop("checked",true);
		if (item == 0) {
			$("#otherDangerFactor").val(data.otherDangerFactor);
		}
	});
	/*------------管理危害因素.end------------*/
	
	/*------------可能造成的事故类型.start------------*/
	var accidentTypeArr = data.accidentType.split(",");  
	$.each(accidentTypeArr,function(i,item){
		$("input[name='accidentType'][value="+item+"]").prop("checked",true);
	});
	/*------------可能造成的事故类型.end------------*/
	
	$("#pivotalMeasure").val(data.pivotalMeasure);//关键作业步骤，主要风险及控制措施
	$("#dangerDescribe").val(data.dangerDescribe);//险情描述
	$("#emergencyResponse").val(data.emergencyResponse);//应急处置措施
	$("#rescueMeasures").val(data.rescueMeasures);//应急救援措施
	$("#safetyMeasures").val(data.safetyMeasures);//现场维护安全措施
	$("#improvementMeasure").val(data.improvementMeasure);//建议改进措施
	$("#workManageUser").val(data.workManageUser);//作业管理人员
	$("#workHandleUser").val(data.workHandleUser);//作业操作人员
	$("#workTutelageUser").val(data.workTutelageUser);//作业监护人员
}
/*-------------编辑获取值.end-------------*/